package cn.it.shop.service.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import cn.it.shop.service.BaseService;

@SuppressWarnings(value={"unchecked","rawtypes"})
@Service("baseService")
@Lazy(true)
public class BaseServiveImpl<T> implements BaseService<T> {

	private Class			clazz;

	@Resource
	// 没有指定名称，默认是属性名称与id捆绑
	private SessionFactory	sessionFactory;

	// public void setSessionFactory(SessionFactory sessionFactory) {
	// this.sessionFactory = sessionFactory;
	// }

	public BaseServiveImpl() {
		System.out.println("this代表当前调用构造方法的对象：" + this);
		System.out
				.println("获取当前this对象的父类信息:" + this.getClass().getSuperclass());
		System.out.println("获取当前this对象的父类信息(包括泛型信息):"
				+ this.getClass().getGenericSuperclass());
		ParameterizedType type = (ParameterizedType) this.getClass()
				.getGenericSuperclass();
		clazz = (Class) type.getActualTypeArguments()[0];
	}

	protected Session getSession() {
		// 从当前线程获取session 如果没有获取新的session
		return sessionFactory.getCurrentSession();
	}

	public void save(T t) {
		getSession().save(t);
	}

	public void delete(int id) {
		String hql = "DELETE " + clazz.getSimpleName() + " WHERE id=:id";
		getSession().createQuery(hql).setInteger("id", id).executeUpdate();
	}

	public List<T> query() {
		String hql = "FROM " + clazz.getSimpleName();
		return getSession().createQuery(hql).list();
	}

	public void update(T t) {
		getSession().update(t);
	}

	public T get(int id) {
		return (T) getSession().get(clazz, id);
	}

}
